package com.leet.tree;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class DelNodes {
    // 重点：后序遍历，先遍历到最底层然后执行删除操作。
    // 两个函数都要用的，放在外面
    Set<Integer> st;
    List<TreeNode> forest;
    public List<TreeNode> delNodes(TreeNode root, int[] to_delete) {
        st = new HashSet<>();
        forest = new ArrayList<>();
        for(int i:to_delete) {
            st.add(i);
        }
        root = helper(root);
        if (root != null){
            forest.add(root);
        }
        return forest;
    }
    public TreeNode helper(TreeNode root){
        if(root == null) return root;
        root.left=helper(root.left);
        root.right=helper(root.right);
        if(st.contains(root.val)){
            if(root.left != null) forest.add(root.left);
            if(root.right != null) forest.add(root.right);
            // root删除掉
            root = null;
        }
        return root;
    }
}
